//
//  UserEditViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/23.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class UserEditViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    var cameraBtn: UIButton!
    
    var nickNameInput: UITextField!
    var sexSelector: UISegmentedControl!
    
    var loadingView: LLFullScreenLoading!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        title = "完善资料"
        navigationController?.setNavigationBarHidden(true, animated: false)
        
        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        navBar.barTintColor = themeColor2
        navBar.barStyle = .black
        navBar.tintColor = UIColor.white
        
        
        let navItem = UINavigationItem(title: "完善资料")
        navItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(UserEditViewController.goBack))
        navItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "arrow_white"), style: .plain, target: self, action: #selector(UserEditViewController.nextStep))
        
        navBar.pushItem(navItem, animated: true)
        
        cameraBtn = UIButton(frame: CGRect(x: 0, y: 80, width: 100, height: 100))
        cameraBtn.center.x = view.center.x
        cameraBtn.layer.cornerRadius = 50
        cameraBtn.layer.borderColor = themeColor2.cgColor
        cameraBtn.layer.borderWidth = 1
        cameraBtn.layer.masksToBounds = true
        view.addSubview(cameraBtn)
        cameraBtn.addTarget(self, action: #selector(UserEditViewController.uploadAvatar), for: .touchUpInside)
        
        let cameraImg = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        cameraImg.center = CGPoint(x: 50, y: 50)
        cameraImg.image = #imageLiteral(resourceName: "camera")
        cameraImg.contentMode = .scaleAspectFit
        cameraBtn.addSubview(cameraImg)
        
        let nickNameRow = UIView(frame: CGRect(x: 0, y: 200, width: view.bounds.width - 128, height: 44))
        nickNameRow.center.x = view.center.x
        
        view.addSubview(nickNameRow)
        
        let nickNameLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 64, height: 44))
        nickNameLabel.text = "昵称: "
        nickNameRow.addSubview(nickNameLabel)
        
        nickNameInput = UITextField(frame: CGRect(x: 64, y: 0, width: nickNameRow.frame.width - 64, height: 44))
        nickNameInput.placeholder = "请输入昵称"
        nickNameInput.returnKeyType = .done
        nickNameInput.enablesReturnKeyAutomatically = true
        nickNameRow.addSubview(nickNameInput)
        nickNameInput.addTarget(self, action: #selector(UserEditViewController.inputEnd(sender:)), for: .editingDidEndOnExit)
        nickNameInput.text = FCUserReg.shared.username
        
        let line = UIView(frame: CGRect(x: 64, y: 40, width: nickNameInput.frame.width, height: 1))
        line.backgroundColor = UIColor.lightGray
        nickNameRow.addSubview(line)
        
        let sexRow = UIView(frame: CGRect(x: 0, y: 244, width: view.bounds.width - 128, height: 44))
        sexRow.center.x = view.center.x
        view.addSubview(sexRow)
        
        let sexLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 64, height: 44))
        sexLabel.text = "性别: "
        sexRow.addSubview(sexLabel)
        
        sexSelector = UISegmentedControl(items: ["男", "女", "保密"])
        sexSelector.frame = CGRect(x: 64, y: 8, width: sexRow.frame.width - 64, height: 28)
        sexSelector.tintColor = themeColor1
        sexSelector.selectedSegmentIndex = 2
        sexRow.addSubview(sexSelector)
        
        view.addSubview(navBar)
        
        loadingView = LLFullScreenLoading(frame: view.frame)
        loadingView.alpha = 0
    }

    func inputEnd(sender: UITextField){
        sender.resignFirstResponder()
    }
    
    func nextStep(){
        if checkInput(){
            postRegRequest()
        }
    }
    
    func checkInput() -> Bool{
        if nickNameInput.text == "" {
            
            nickNameInput.becomeFirstResponder()
            return false
        }
        
        
        
        return true
    }
    
    func getSexName(withID: Int) -> String {
        switch withID {
        case 1:
            return "男"
        case 2:
            return "女"
        default:
            return "保密"
        }
    }
    
    func postRegRequest(){
        if FCUserReg.shared.isRegisterStarted{
            loadingView.alpha = 1
            
            FCUserReg.shared.nickName = nickNameInput.text
            FCUserReg.shared.sex = getSexName(withID: (sexSelector.selectedSegmentIndex + 1) % 3)
            
            FCUserReg.shared.initCommitUserInfo(successHandler: { (data) in
                DispatchQueue.main.async {
                    self.loadingView.alpha = 0
//                    FCUserReg.shared.wodeVC?.loadUserData()
                    self.dismiss(animated: true, completion: nil)
                }
                
            }, failedHandler: { (err) in
                print(err ?? "")
                DispatchQueue.main.async {
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    self.present(alert, animated: true, completion: nil)
                }
                
            })
        }
    }
    
    func uploadAvatar(){
        let options = UIAlertController(title: "修改头像", message: nil, preferredStyle: .actionSheet)
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.allowsEditing = true
        options.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (action) in
            
            if UIImagePickerController.isCameraDeviceAvailable(.rear) || UIImagePickerController.isCameraDeviceAvailable(.front) {
                picker.sourceType = .camera
                self.present(picker, animated: true, completion: nil)
            }else{
                let alert = UIAlertController(title: "无法打开相机", message: "设置-隐私-相机-喵印-打开", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
            
        }))
        options.addAction(UIAlertAction(title: "选择照片", style: .default, handler: { (action) in
            picker.sourceType = .photoLibrary
            self.present(picker, animated: true, completion: nil)
        }))
        options.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(options, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        DispatchQueue.main.async {
            picker.dismiss(animated: true, completion: nil)
        }
        
        let image = info[UIImagePickerControllerEditedImage] as? UIImage
        if image != nil{
            
            
            let smallSize = CGSize(width: 150, height: 150)
            
            UIGraphicsBeginImageContext(smallSize)
            image!.draw(in: CGRect(origin: CGPoint.zero, size: smallSize))
            let smallImage = UIGraphicsGetImageFromCurrentImageContext()
            
            DispatchQueue.main.async {
                self.cameraBtn.setImage(smallImage, for: .normal)
            }
            
            if smallImage != nil{
                let imageData = UIImageJPEGRepresentation(smallImage!, 0.5)
                
                var postData = Data()
                
                postData.append("--AaB03x\r\nContent-Disposition: form-data; name=\"face\"; filename=\"filename.jpg\"\r\nContent-Type: image/jpg\r\n\r\n".data(using: .utf8)!)
                postData.append(imageData!)
                postData.append("\r\n--AaB03x--\r\n".data(using: .utf8)!)
                
                var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=index&a=editInfo")!)
                resq.httpMethod = "POST"
                resq.setValue("multipart/form-data; boundary=AaB03x", forHTTPHeaderField: "Content-Type")
                resq.setValue("\(postData.count)", forHTTPHeaderField: "Content-Length")
                print(resq.allHTTPHeaderFields ?? "nil")
                resq.httpBody = postData
                
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, er:Error?) in
                    do{
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        let code = jsonObj?.object(forKey: "code") as? Int
                        if code != 200 {
                            let msg = jsonObj?.object(forKey: "message") as? String
                            let alert = UIAlertController(title: msg, message: nil, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            DispatchQueue.main.async {
                                self.present(alert, animated: true, completion: nil)
                            }
                        }
                    }catch let ex{
                        let alert = UIAlertController(title: "头像上传失败", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                        print(ex)
                    }
                }).resume()
            }
            
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func goBack(){
//        _ = navigationController?.popViewController(animated: true)
//        FCUserReg.shared.wodeVC?.loadUserData()
        
        FCUserReg.shared.initCommitUserInfo(successHandler: { (data) in
            DispatchQueue.main.async {
                self.loadingView.alpha = 0
                self.dismiss(animated: true, completion: nil)
            }
            
        }, failedHandler: { (err) in
            print(err ?? "")
            DispatchQueue.main.async {
                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
            
        })
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
